from django.shortcuts import render, HttpResponse
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import os
import json
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import seaborn as sns
from imblearn.over_sampling import SMOTE
from sklearn.feature_selection import RFE
import statsmodels.api as sm
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve

from .mysqldemo.mysqltest import *
import time


# Create your views here.
def index(request):
    return render(request, "index.html")


def vue_test(request):
    # data_file = os.getcwd() + "\\homework\\projects\\demo2\\starcraft.csv"
    data = [5, 20, 36, 10, 10, 20]
    df = pd.DataFrame(data)
    print(df)
    # pd.read_csv('')
    # df_json = df.head(2).to_json(orient="records", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="index", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="table")
    df_json = df.to_json(orient="values")
    return HttpResponse(df_json)


def heart_age(request):
    df = pd.read_csv("static\heart\整理好的心血管数据.csv")
    print(df)

    df_age = df.loc[:, ['years', 'cardio']]
    df_age_sort = df_age.sort_values(by='years')
    df0 = df_age_sort[df_age_sort["cardio"] == 0]["years"]
    df1 = df_age_sort[df_age_sort["cardio"] == 1]["years"]
    # 把 年龄 和 是否患病 提取出来

    df0n = df0.value_counts()
    df1n = df1.value_counts()

    a = pd.DataFrame()
    a["0"] = df0n
    a["1"] = df1n
    a.fillna(0, inplace=True)
    a = a.sort_index()
    df_json = a.to_json(orient="split")
    # df_json = a.head().to_json(orient="split")

    # df_json = df.head(2).to_json(orient="records", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="index", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="columns", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="split", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="table")
    return HttpResponse(df_json)


def heart_gender(request):
    # 2 == 男性     1 == 女性
    df = pd.read_csv("static\heart\整理好的心血管数据.csv")
    print(df)

    df_gender = df.loc[:, ['gender', 'cardio']]
    df0 = df_gender[df_gender["cardio"] == 0]
    df1 = df_gender[df_gender["cardio"] == 1]
    # 把 性别 和 是否患病 提取出来

    df0_man = df0[df0["gender"] == 2]
    df0_wman = df0[df0["gender"] == 1]
    #  提取未患病 男女信息

    df1_man = df1[df1["gender"] == 2]
    df1_wman = df1[df1["gender"] == 1]
    #  提取 患病 男女信息

    # data_num = {"男性":{"患":11,"不患":12},"女性":{"患":7,"不患":8}}
    data_num = {"male": {"1": df1_man.count().gender, "0": df0_man.count().gender},
                "female": {"1": df1_wman.count().gender, "0": df0_wman.count().gender}}
    data_nu = pd.DataFrame(data_num)
    df_json = data_nu.to_json(orient="columns")

    # df_json = df.head(2).to_json(orient="records", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="index", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="table")
    return HttpResponse(df_json)


def heart_height(request):
    # 2 == 男性     1 == 女性
    df = pd.read_csv("static\heart\整理好的心血管数据.csv")
    print(df)

    df_height = df.loc[:, ['height', 'cardio']]
    df0 = df_height[df_height["cardio"] == 0]
    df1 = df_height[df_height["cardio"] == 1]
    # 把 性别 和 是否患病 提取出来

    a = pd.DataFrame(list(zip(df0["height"], df1["height"])))

    df_json = a.head(2000).to_json(orient="split")

    # df_json = df.head(2).to_json(orient="records", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="index", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="table")
    return HttpResponse(df_json)


def heart_weight(request):
    # 2 == 男性     1 == 女性
    df = pd.read_csv("static\heart\整理好的心血管数据.csv")
    print(df)

    df_weight = df.loc[:, ['weight', 'cardio']]
    df0 = df_weight[df_weight["cardio"] == 0]
    df1 = df_weight[df_weight["cardio"] == 1]
    # 把 性别 和 是否患病 提取出来

    a = pd.DataFrame(list(zip(df0["weight"], df1["weight"])))

    df_json = a.head().to_json(orient="split")

    # df_json = df.head(2).to_json(orient="records", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="index", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="table")
    return HttpResponse(df_json)


def heart_relation(request):
    # 2 == 男性     1 == 女性
    df = pd.read_csv("static\heart\整理好的心血管数据.csv")
    df.drop(columns=['id'], inplace=True)
    print(df)
    corr = df.corr()
    corrf = corr.iloc[::-1]

    df_json = corrf.to_json(orient="split")

    # df_json = df.head(2).to_json(orient="records", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="index", date_format = 'ISO8601', date_unit = 's')
    # df_json = df.head(2).to_json(orient="table")
    return HttpResponse(df_json)


def heart_bmi(request):
    # 2 == 男性     1 == 女性
    df = pd.read_csv("static\heart\整理好的心血管数据.csv")
    df.drop(columns=['id'], inplace=True)
    print(df)
    df['BMI'] = df['weight'] / ((df['height'] / 100) ** 2)
    df_1 = df.loc[:10000, ["cardio", 'gender', 'alco', 'BMI']]
    df_json = df_1.head(2000).to_json(orient="index")

    return HttpResponse(df_json)


def diabetes_age(request):
    df = pd.read_csv("static\diabetes\diabetes_data_upload.csv")
    df.columns = ['age', 'gender', 'polyuria', 'polydipsia', 'swl', 'weak', 'polyphagia', 'gt', 'vb',
                  'itch', 'irritate', 'dh', 'pp', 'ms', 'alopesia', 'obesity', 'class']

    le = preprocessing.LabelEncoder()
    for i in df.columns:
        encode = le.fit_transform(df[i])
        df[i] = encode
    df.head()
    dd = pd.crosstab(df['age'], df['class'])
    df_json = dd.to_json(orient="index")

    return HttpResponse(df_json)


def diabetes_test(request):
    d = pd.read_csv("static\diabetes\diabetes_data_upload.csv")
    d.columns = ['age', 'gender', 'polyuria', 'polydipsia', 'swl', 'weak', 'polyphagia', 'gt', 'vb',
                 'itch', 'irritate', 'dh', 'pp', 'ms', 'alopesia', 'obesity', 'class']

    le = preprocessing.LabelEncoder()
    for i in d.columns:
        encode = le.fit_transform(d[i])
        d[i] = encode
    d.head()

    X = d.loc[:, d.columns != 'class']
    y = d.loc[:, d.columns == 'class']

    os = SMOTE(random_state=0)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

    columns = X_train.columns
    os_data_X, os_data_y = os.fit_sample(X_train, y_train)

    print("length of oversampled data is ", len(os_data_X))
    print("Number of no diabetes in oversampled data", len(os_data_y[os_data_y['class'] == 0]))
    print("Number of people with diabetes", len(os_data_y[os_data_y['class'] == 1]))
    print("Proportion of no diabetes data in oversampled data is ",
          len(os_data_y[os_data_y['class'] == 0]) / len(os_data_X))
    print("Proportion of diabetes data in oversampled data is ",
          len(os_data_y[os_data_y['class'] == 1]) / len(os_data_X))
    d_vars = d.columns.values.tolist()
    y = ['class']
    X = [i for i in d_vars if i not in y]
    logreg = LogisticRegression()

    rfe = RFE(logreg, 20)
    ##这里的20指的是number of features to select, 只要填大于variables的数量的数字即可

    rfe = rfe.fit(os_data_X, os_data_y)
    print(rfe.support_)
    print(rfe.ranking_)

    ###开始使用逻辑回归模型
    logit_model = sm.Logit(y_train, X_train)
    result = logit_model.fit()
    print(result.summary2())

    logit_model = sm.Logit(os_data_y, os_data_X)
    result = logit_model.fit()
    print(result.summary2())

    logit_model = sm.Logit(y_test, X_test)
    result = logit_model.fit()
    print(result.summary2())

    logreg = LogisticRegression()
    logreg.fit(X_train, y_train)

    LogisticRegression()

    y_pred = logreg.predict(X_test)
    print('Accuracy of logistic regression classifier on test set: {:.2f}'.format(logreg.score(X_test, y_test)))

    ##绘制一个roc curve来检验模型。
    ###roc curve距离直线越远越好

    logit_roc_auc = roc_auc_score(y_test, logreg.predict(X_test))
    fpr, tpr, thresholds = roc_curve(y_test, logreg.predict_proba(X_test)[:, 1])
    plt.figure()
    plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)
    plt.plot([0, 1], [0, 1], 'r--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic')
    plt.legend(loc="lower right")
    plt.savefig('Log_ROC')
    plt.show()

    return HttpResponse('123')


def diabetes_att(request):
    d = pd.read_csv("static\diabetes\diabetes_data_upload.csv")
    d.columns = ['age', 'gender', 'polyuria', 'polydipsia', 'swl', 'weak', 'polyphagia', 'gt', 'vb',
                 'itch', 'irritate', 'dh', 'pp', 'ms', 'alopesia', 'obesity', 'class']
    le = preprocessing.LabelEncoder()
    for i in d.columns:
        encode = le.fit_transform(d[i])
        d[i] = encode
    d.head()
    # d0 = d[d['class'] == 0]
    # d1 = d[d['class'] == 1]

    # dff = d.groupby('class').count()
    dff = d.groupby('class').mean()
    age_dff = dff['age']
    age_dff = (age_dff) / (age_dff.max() + age_dff.min())
    dff['age'] = age_dff
    # del dff['age']
    # age_sum = dff['age'].sum()

    # df_json = """ '{"0":"""+ d0.to_json(orient="columns")+"""},{"1":"""+d1.to_json(orient="columns")+"""}'"""
    df_json = dff.to_json(orient="index")
    return HttpResponse(df_json)


def login_query(request):
    # num1 = request.POST.get('num1')
    # < QueryDict: {'userName': ['1'], 'password': ['23']} >

    print(request.POST)
    userName = request.POST.get('userName')
    password = request.POST.get('password')
    # print("userName: "+userName)
    # print("password: "+password)
    res = {"resCode": 0,"resObj":{"userId":-1,"userName":"未定义","loginIp":"192.168.2.45","loginTime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),"ipAddr": "亚洲"}}
    # resObj{
    #     userName: null,
    #     loginIp: "192.168.2.45",
    #     loginTime: Date.now(),
    #     ipAddr: "亚洲",
    # }
    conn = get_conn()
    sql = "select id,pwd,adminpower from a_zucc_school_project_users where id = {0}".format(userName)
    result = query_data(conn, sql)
    # print(result)
    id = result[0]['id']
    pwd = result[0]['pwd']
    power = result[0]['adminpower']
    if (pwd == password):
        res["resCode"] = 1
        res["resObj"]["userName"] = "普通编号： "+ str(id)
        res["resObj"]["userId"] = power
    if(power == 1):
        res["resObj"]["userName"] = "管理员： " + str(id)
    res = json.dumps(res)
    return HttpResponse(res)


def login_listMenu(request):
    # num1 = request.POST.get('num1')
    # < QueryDict: {'userName': ['1'], 'password': ['23']} >

    dateString = getTimeString()
    conn = get_conn()
    sql = "select fvalues from a_zucc_school_project_access where keyindex = '{0}'".format(dateString)
    result = query_data(conn, sql)
    if(result):
        values = result[0]['fvalues']
        values = values + 1
        conn = get_conn()
        sql = "UPDATE a_zucc_school_project_access SET fvalues={0} WHERE keyindex = '{1}'".format(values,dateString)
        result = insert_or_update_data(conn, sql)
    else:
        conn = get_conn()
        sql = "INSERT INTO a_zucc_school_project_access VALUES (null, '{0}',1)".format(dateString)
        result = insert_or_update_data(conn, sql)


    print("login_listMenu"+str(request.POST))
    power = request.POST.get("userId")
    print(power)
    if(power == '1'):
        data = [{"index": "home", "title": "首页", "path": "home", },
                {"index": "heart", "title": "心血管疾病",
                 "child": [{"index": "heart/heart1", "title": "心血管疾病 1", "path": "heart/heart1", },
                           {"index": "heart/heart2", "title": "心血管疾病 2", "path": "heart/heart2", }, ], },
                {
                    "index": "diabetes",
                    "title": "糖尿病",
                    "child": [
                        {
                            "index": "diabetes/diabetes1",
                            "title": "糖尿病1",
                            "path": "diabetes/diabetes1",
                        },
                        {
                            "index": "diabetes/diabetes2",
                            "title": "糖尿病2",
                            "path": "diabetes/diabetes2",
                        },
                    ],
                },
                {
                    "index": "grop",
                    "title": "用户详情",
                    "child": [
                        {
                            "index": "grop/grop1",
                            "title": "个人信息",
                            "path": "grop/grop1",
                        },
                        {
                            "index": "grop/grop2",
                            "title": "整体信息",
                            "path": "grop/grop2",
                        },
                        {
                            "index": "grop/grop3",
                            "title": "物联设备",
                            "path": "grop/grop3",
                        },
                    ],
                },
                ]
    else:
        data = [{"index": "home", "title": "首页", "path": "home", },
                {
                    "index": "grop",
                    "title": "用户详情",
                    "child": [
                        {
                            "index": "grop/grop1",
                            "title": "个人信息",
                            "path": "grop/grop1",
                        },
                    ],
                },
                ]
    pp = {}
    pp["resObj"] = data
    pp["resCode"] = 1
    res = json.dumps(pp)
    return HttpResponse(res)

def grop_getall(request):
    conn = get_conn()
    sql = "select * from a_zucc_school_project_users"
    res = query_data(conn, sql)
    res = res[:68]
    df_json = json.dumps(res)
    return HttpResponse(df_json)

def gropGetFacilityAll(request):
    conn = get_conn()
    sql = "select * from a_zucc_school_project_facility"
    res = query_data(conn, sql)
    res.reverse()
    res = res[:68]
    df_json = json.dumps(res)
    return HttpResponse(df_json)

def grop_person(request):
    user_id = request.POST.get('userName')[-1]
    conn = get_conn()
    print(user_id)
    sql = "select * from a_zucc_school_project_users where id = {0}".format(user_id)
    res = query_data(conn, sql)
    data = pd.DataFrame(res)
    dataf = data.iloc[:, 3:]

    df_json = dataf.to_json(orient="split")
    return HttpResponse(df_json)

def grop_average(request):
    user_id = 1
    conn = get_conn()
    print(user_id)
    sql = "select * from a_zucc_school_project_users where id = {0}".format(user_id)
    res = query_data(conn, sql)
    data = pd.DataFrame(res)
    dataf = data.iloc[:, 3:]

    df_json = dataf.to_json(orient="split")
    return HttpResponse(df_json)

def getTimeStringWithDate():
    # '1,2,3'.split(',')
    # arr = ['a','b']       str = ','.join(arr)
    fulltime = time.strftime('%Y_%m_%d_%H', time.localtime(time.time()))
    return fulltime
def getTimeString():
    # '1,2,3'.split(',')
    # arr = ['a','b']       str = ','.join(arr)
    fulltime = time.strftime('%Y_%m_%d', time.localtime(time.time()))
    return fulltime


def getAllAccess(request):
    conn = get_conn()
    sql = "SELECT COUNT(fvalues) as allnum FROM a_zucc_school_project_access"
    result = query_data(conn,sql)
    values = result[0]["allnum"]
    return HttpResponse(values)

def getDayAccess(request):
    date = getTimeString()
    conn = get_conn()
    sql = "SELECT fvalues as accessnum FROM a_zucc_school_project_access WHERE keyindex='{0}'".format(date)
    result = query_data(conn,sql)
    values = result[0]
    return HttpResponse(json.dumps(values))

def getAllAccess(request):
    conn = get_conn()
    sql = "SELECT fvalues as allaccessnum FROM a_zucc_school_project_access"
    result = query_data(conn,sql)
    pp = pd.DataFrame(result)
    values = pp.sum()
    return HttpResponse(values.to_json())

def accountGetAllNum(request):
    conn = get_conn()
    sql = "select * from a_zucc_school_project_users"
    res = query_data(conn, sql)
    values = pd.DataFrame(res)
    accountallnum = values.shape[0]
    a = {'accountallnum':0}
    a['accountallnum'] = accountallnum
    return HttpResponse(json.dumps(a))

def getAllDataNum(request):
    data1 = pd.read_csv("static\diabetes\diabetes_data_upload.csv")
    data2 = pd.read_csv("static\heart\整理好的心血管数据.csv")
    data3 = pd.read_csv("static\heart.csv")

    num = 0
    num = num + data1.shape[0]
    num = num + data2.shape[0]
    num = num + data3.shape[0]
    a = {'alldatanum':0}
    a['alldatanum'] = num
    return HttpResponse(json.dumps(a))